<template>
  <div class="app-container">
    <!-- 基本信息卡片 -->
    <el-card class="box-card" style="margin-bottom: 20px;">
      <template #header>
        <div class="card-header">
          <h2>基本信息</h2>
        </div>
      </template>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="血型">{{ baseInfo.bloodType || '暂无数据' }}</el-descriptions-item>
        <el-descriptions-item label="既往病史">{{ baseInfo.medicalHistory || '无' }}</el-descriptions-item>
        <el-descriptions-item label="过敏史">{{ baseInfo.allergyHistory || '无' }}</el-descriptions-item>
        <el-descriptions-item label="身高体重">{{ baseInfo.height }}cm / {{ baseInfo.weight }}kg</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 健康记录卡片 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>健康记录历史</h2>
        </div>
      </template>

      <el-table
          :data="healthData"
          border
          stripe
          style="width: 100%"
          v-loading="loading"
          element-loading-text="数据加载中..."
          element-loading-background="rgba(255, 255, 255, 0.8)"
      >
        <el-table-column
            prop="recordDate"
            label="记录日期"
            width="150"
            align="center"
        ></el-table-column>

        <el-table-column
            prop="staffName"
            label="负责护工"
            width="120"
            align="center"
        >
        </el-table-column>

        <el-table-column
            prop="bloodPressure"
            label="血压(mmHg)"
            width="120"
            align="center"
        >
          <template #default="{row}">
            <el-tag v-if="row.bloodPressure" type="info">
              {{ row.bloodPressure }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
            prop="heartRate"
            label="心率(bpm)"
            width="110"
            align="center"
        >
          <template #default="{row}">
            <div :class="{'warning-text': row.heartRate > 100}">
              {{ row.heartRate || '-' }}
            </div>
          </template>
        </el-table-column>

        <el-table-column
            prop="bloodSugar"
            label="血糖(mmol/L)"
            width="130"
            align="center"
        >
          <template #default="{row}">
            <div :class="{
              'warning-text': row.bloodSugar > 6.1 || row.bloodSugar < 3.9
            }">
              {{ row.bloodSugar?.toFixed(1) || '-' }}
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="doctorSuggestions" label="医生建议">
          <template #default="{row}">
            <div style="white-space: pre-wrap;">{{ row.doctorSuggestions || '暂无建议' }}</div>
          </template>
        </el-table-column>
      </el-table>

      <div style="margin-top: 20px">
        <el-pagination
            @current-change="currentChange"
            @size-change="sizeChange"
            :page-size="pageInfo.pageSize"
            :current-page="pageInfo.pageNum"
            background
            layout="total,sizes, prev, pager, next"
            :total="pageInfo.total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import {ref, onMounted, reactive, toRaw} from 'vue'
import http from '@/utils/http.js'
import utils from "@/utils/tools.js";
import { ElMessage } from 'element-plus'

const baseInfo = ref({
  bloodType: '',
  medicalHistory: '',
  allergyHistory: '',
  height: '-',
  weight: '-',
  elderId: '',
})

const healthData = ref([])

const pageInfo = ref({
  //当前页
  pageNum: 1,
  //分页大小
  pageSize: 10,
  //总条数
  total: 0
});

const loading = ref(false)

onMounted(async () =>  {
  await getElderInfo()
  if (baseInfo.value.elderId) {  // 改为检查有效值
    await getPageList()
  }
})

async function getElderInfo() {
  try {
    const res = await http.get(`/elder/selectByFamilyId/${utils.getCurrentUser().id}`)
    const data = res.data
    if (data) {
      baseInfo.value = {
        bloodType: data.bloodType || '未知',
        medicalHistory: data.medicalHistory || '无',
        allergyHistory: data.allergyHistory || '无',
        height: data.height || '-',
        weight: data.weight || '-',
        elderId: data.id
      }
    }

  } catch (e) {
    console.error('获取基本信息失败:', e)
    ElMessage.error('基本信息加载失败')
  }
}

console.log('baseInfo:', baseInfo)
if (baseInfo.value.elderId !== undefined){
  getPageList()
}

/**
 * 选择分页
 * @param e
 */
function currentChange(e) {
  pageInfo.value.pageNum = e
  getPageList()
}

/**
 * 改变分页数量
 * @param e
 */
function sizeChange(e) {
  pageInfo.value.pageSize = e
  getPageList()
  console.log(e)
}

/**
 * 搜索
 */
function search() {
  pageInfo.value.pageNum = 1
  getPageList()
}

/**
 * 重置搜索框
 */
function resetSearch() {
  searchFormComponents.value.resetFields();
  getPageList()
}

/**
 * 获取分页数据
 */
async function getPageList() {
  if (!baseInfo.value.elderId) {
    return
  }
  loading.value = true

  try {
    console.log('baseInfo.value.elderId:', baseInfo.value.elderId)
    const params = {
      pageNum: pageInfo.value.pageNum,
      pageSize: pageInfo.value.pageSize,
      elderId: baseInfo.value.elderId,
    }
    console.log('请求参数:', params)
    const res = await http.get(`/health_record/page`, { params })
    healthData.value = res.data.list
    pageInfo.value.total = res.data.total
    console.log('响应数据:', res.data)
  } catch (e) {
    console.error('获取数据失败:', e)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.warning-text {
  color: #e6a23c;
  font-weight: 500;
}
</style>